package com.zwh.mangomall.controller;

import com.zwh.mangomall.service.ex.*;
import com.zwh.mangomall.service.ex.ServiceException;
import com.zwh.mangomall.util.ResultCode;
import com.zwh.mangomall.util.ResultMsg;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ServiceException.class)
    public ResultMsg handleCustomException(Throwable e){
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setMsg(e.getMessage());
        if (e instanceof EmptyArgumentException){
            resultMsg.setCode(ResultCode.PARAMS_IS_NULL);
        }else if (e instanceof InsertException){
            resultMsg.setCode(ResultCode.INSERT_FAIL);
        }else if (e instanceof UpdateException){
            resultMsg.setCode(ResultCode.UPDATE_FAIL);
        }else if (e instanceof LoginException){
            resultMsg.setCode(ResultCode.LOGIN_FAIL);
        }

        return resultMsg;
    }
}
